<template>
	<div class="mainsu">
		<div class="main_spac1">
			<div class="main_white padding10 paddingBottom20">
				<div class="mainor_form">
					<div class="mainor_te">
						<el-button type="primary" @click="exportform">导出</el-button>
					</div>
					<el-form
						:inline="true"
						:model="form"
						class="demo-form-inline"
						ref="userListFrom"
						label-width="70px"
					>
						<el-form-item label="" prop="date_type" class="wid110">
							<el-select v-model="form.date_type" placeholder="请选择">
								<el-option label="采购日期" value="1"> </el-option>
								<el-option label="创建日期" value="2"> </el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="" prop="establishTime">
							<el-date-picker
								v-model="establishTime"
								type="daterange"
								class="time220"
								:editable="false"
								unlink-panels
								range-separator="至"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								value-format="yyyy-MM-dd"
								:clearable="false"
								:picker-options="pickerOptions"
								@change="dateChange"
							/>
						</el-form-item>
						<div class="more el-form-item" @click="moredata = !moredata">
							<span>更多</span>
							<i :class="[{ on: moredata }, ' el-icon-arrow-down']"></i>
						</div>
						<div class="clearfix"></div>
						<el-collapse-transition>
							<div v-if="moredata" style="width: 100%">
								<div>
									<el-form-item label="商品名称" prop="goods_spu_id">
										<change-goods-input
											ref="changeGoodsInput"
											@clear="
												() => {
													this.form.goods_spu_id = '';
												}
											"
											@sendValue="
												(data) => {
													this.form.goods_spu_id = data.id;
												}
											"
										></change-goods-input>
									</el-form-item>
									<el-form-item label="商品分类" prop="category_id">
										<el-cascader
											v-model="form.category_id"
											:options="options"
											:props="defaultProps"
										></el-cascader>
									</el-form-item>
									<el-form-item label="采购方式" prop="mode">
										<el-select
											v-model.trim="form.mode"
											placeholder="采购方式"
											class="wid110"
										>
											<el-option label="所有" value=""></el-option>
											<el-option label="采购员" value="1"></el-option>
											<el-option label="供应商" value="2"></el-option>
										</el-select>
										<el-select
											v-show="form.mode == 1"
											v-model.trim="form.buyer_id"
											placeholder="采购员"
											class="wid220"
										>
											<el-option label="所有" value=""></el-option>
											<el-option
												v-for="(buyer, index) in buyer"
												:key="index"
												:label="buyer"
												:value="parseInt(index)"
											></el-option>
										</el-select>
										<el-select
											v-show="form.mode == 2"
											v-model.trim="form.supplier_id"
											placeholder="供应商"
											class="wid220"
										>
											<el-option label="所有" value=""></el-option>
											<el-option
												v-for="(supplier, index) in supplier"
												:key="index"
												:label="supplier"
												:value="parseInt(index)"
											></el-option>
										</el-select>
										<el-select
											v-show="!form.mode"
											v-model.trim="form_mode_all"
											placeholder="所有"
											class="wid220"
										>
											<el-option label="所有" value=""></el-option>
										</el-select>
									</el-form-item>
								</div>
							</div>
						</el-collapse-transition>
						<el-form-item>
							<el-button
								class="reset marginLeft10"
								type="primary"
								@click="reset"
								>重置</el-button
							>
							<el-button
								type="primary"
								@click="getArticleList"
								:loading="listLoading"
								>搜索</el-button
							>
						</el-form-item>
					</el-form>
				</div>
				<div class="main_table marginTop10" style="min-height: 550px">
					<el-table
						ref="multipleTable"
						v-loading="listLoading"
						:data="list"
						element-loading-text="加载中"
						fit
						border
						highlight-current-row
						:header-cell-class-name="this.$verticaline"
					>
						<el-table-column
							label="商品名称"
							prop="goods_name"
							min-width="120"
							show-overflow-tooltip
						/>
						<el-table-column
							label="单位"
							prop="unit"
							min-width="120"
							show-overflow-tooltip
						/>
						<el-table-column
							label="采购数量"
							prop="purchase_num"
							min-width="120"
							show-overflow-tooltip
						>
						</el-table-column>
						<el-table-column
							label="平均单价"
							prop="avg_price"
							min-width="120"
							show-overflow-tooltip
						>
							<template slot-scope="scope">
								{{ scope.row.avg_price | twoPlace }}
							</template>
						</el-table-column>
						<el-table-column
							label="采购金额"
							prop="purchase_money"
							min-width="120"
							show-overflow-tooltip
						>
							<template slot-scope="scope">
								{{ scope.row.purchase_money | twoPlace }}
							</template>
						</el-table-column>

						<el-table-column
							label="退货数量"
							prop="return_num"
							min-width="120"
							show-overflow-tooltip
						>
						</el-table-column>
						<el-table-column
							label="退货金额"
							prop="return_money"
							min-width="120"
							show-overflow-tooltip
						>
							<template slot="header">
								<headerSortArrow
									label="return_money"
									ref="arrow1"
									@handleSort="handleSort($event, 'arrow1')"
									>退货金额</headerSortArrow
								>
							</template>
							<template slot-scope="scope">
								{{ scope.row.return_money | twoPlace }}
							</template>
						</el-table-column>
						<el-table-column
							label="实采购数量"
							prop="real_num"
							min-width="120"
							show-overflow-tooltip
						>
						</el-table-column>
						<el-table-column
							label="实采购金额"
							prop="real_money"
							min-width="120"
							show-overflow-tooltip
						>
							<template slot="header">
								<headerSortArrow
									label="real_money"
									ref="arrow2"
									@handleSort="handleSort($event, 'arrow2')"
									>实采购金额</headerSortArrow
								>
							</template>
							<template slot-scope="scope">
								{{ scope.row.real_money | twoPlace }}
							</template>
						</el-table-column>
						<el-table-column
							label="管理操作"
							align="center"
							width="120"
							fixed="right"
						>
							<template slot-scope="scope">
								<el-link type="primary" @click="handleDetail(scope.row)"
									>明细</el-link
								>
							</template>
						</el-table-column>
					</el-table>
				</div>
				<div class="main_page boxdq">
					<div></div>
					<!-- 分页 -->
					<div class="main_page_r">
						<el-pagination
							:current-page="current.page"
							:page-sizes="[20, 30, 50, 100]"
							:page-size="limit"
							layout="total, sizes, prev, pager, next, jumper"
							:total="totalCount"
							background
							@size-change="
								(page) => {
									changeLimit(page, 1);
								}
							"
							@current-change="
								(page) => {
									changePage(page, 1);
								}
							"
						/>
					</div>
				</div>
			</div>
		</div>

		<!-- 明细 -->
		<el-drawer
			class="report_drawer drawer_min900"
			title="采购明细"
			size="50%"
			:visible.sync="goods_drawer"
			direction="rtl"
		>
			<div class="drawer_container">
				<div class="drawer_container_header">
					<div class="heder_left">
						<span>{{ drawer_title }}</span>
					</div>
					<div class="header_right">
						<!-- <el-popover
              placement="bottom-start"
              width="600"
              trigger="click"
              @after-enter="showChart"
            >
              <div class="popover_chart">
                <div id="chartBar" style="width: 100%; height: 100%"></div>
              </div>
              <el-button slot="reference">图表</el-button>
            </el-popover> -->
						<el-button @click="showChartnew">图表</el-button>
						<el-button type="primary" @click="export_zcExportSkuDetailPurReport"
							>导出</el-button
						>
					</div>
				</div>
				<div class="drawer_container_main">
					<div class="main_table marginTop10" style="min-height: 400px">
						<el-table
							ref="multipleTable"
							v-loading="drawer_loading"
							:data="drawer_list"
							element-loading-text="加载中"
							fit
							border
							highlight-current-row
							:header-cell-class-name="this.$verticaline"
						>
							<el-table-column label="采购员/供应商" prop="name" />

							<el-table-column label="采购均价" prop="order_money">
								<template slot-scope="scope">
									{{ scope.row.price | twoPlace }}
								</template>
							</el-table-column>
							<el-table-column label="采购数量" prop="purchase_num" />
							<el-table-column label="采购金额" prop="purchase_money">
								<template slot-scope="scope">
									{{ scope.row.purchase_money | twoPlace }}
								</template>
							</el-table-column>

							<el-table-column label="采购日期" prop="purchase_time">
							</el-table-column>
						</el-table>
					</div>
					<div class="main_page boxdq">
						<div></div>
						<!-- 分页 -->
						<div class="main_page_r">
							<el-pagination
								:current-page="current_drawer.page"
								:page-sizes="[20, 30, 50, 100]"
								:page-size="limit_drawer"
								layout="total, sizes, prev, pager, next, jumper"
								:total="totalCount_drawer"
								background
								@size-change="
									(page) => {
										changeLimit(page, 2);
									}
								"
								@current-change="
									(page) => {
										changePage(page, 2);
									}
								"
							/>
						</div>
					</div>
				</div>
			</div>
		</el-drawer>

		<!-- 图表弹窗 -->
		<el-dialog title="采购明细" :visible.sync="dialogTableVisible">
			<div class="popover_chart">
				<div id="chartBar" style="width: 100%; height: 100%"></div>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import {
		get_zcGetGoodsReportList,
		get_zcGetSkuDetailPurReport,
		export_purcahse_sku,
		export_zcExportSkuDetailPurReport,
		get_report_base,
	} from "@/api/report/index";
	import { apiUrl, objKeySort, Md5 } from "@/utils/public";
	import { report_shortcuts } from "@/options/new_dateOption";
	import { parseTime, getNowMonth, exportMethod } from "@/utils/index";
	import { recursion, category } from "@/utils/index";
	import echarts from "echarts";
	import { EleResize } from "@/utils/esresize.js";
	import { title } from "@/settings";
	import headerSortArrow from "@/views/report/components/headerSortArrow";

	export default {
		components: { headerSortArrow },
		data() {
			return {
				pickerOptions: report_shortcuts,
				exportMethod,
				// 时间
				parseTime,
				getNowMonth,
				no_data_img: require("@/assets/images/no_data.png"),
				// 分页
				current: {
					page: 1,
					per_page: 20,
				},
				limit: 20,
				totalCount: 1,
				// 列表数据
				list: [],
				listLoading: false,
				buyer: {},
				supplier: {},
				form_mode_all: "",
				// 搜索
				form: {
					goods_spu_id: "",
					start_time: "",
					end_time: "",
					category_id: "",
					mode: "",
					supplier_id: "",
					buyer_id: "",
					date_type: "1",
					order_by: "",
					order_type: "",
				},
				moredata: false,
				// 分类
				options: [],
				defaultProps: {
					children: "selfNext",
					label: "title",
					value: "id",
					checkStrictly: true,
				},
				establishTime: [],
				goods_drawer: false, //商品明细抽屉
				current_drawer: {
					page: 1,
					per_page: 20,
				},
				limit_drawer: 20,
				totalCount_drawer: 1,
				drawer_list: [],
				drawer_loading: false,
				drawer_title: "",
				drawer_form: {
					start_time: "",
					end_time: "",
					goods_spu_id: "",
				},
				// 图表数据
				chart_list: [],
				dialogTableVisible: false,
			};
		},
		watch: {
			"form.mode": {
				handler(val) {
					if (val == 1) {
						this.form.supplier_id = null;
					} else if (val == 2) {
						this.form.buyer_id = null;
					} else if (!val) {
						this.form.supplier_id = null;
						this.form.buyer_id = null;
					}
				},
				deep: true,
			},
		},
		created() {
			this.establishTime = this.getNowMonth();
			this.get_report_base();
			// 列表
			this.get_zcGetGoodsReportList();
		},
		methods: {
			// 基本信息
			get_report_base() {
				let data = Object.assign(
					{
						sign: Md5(
							objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
						),
					},
					apiUrl().name
				);
				get_report_base(data).then((res) => {
					if (res.errcode == 0) {
						this.supplier = res.data.supplier;
						this.buyer = res.data.buyer;
					}
				});
			},
			// 商品列表
			get_zcGetGoodsReportList() {
				this.listLoading = true;
				let data = Object.assign(
					{
						sign: Md5(
							objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
						),
					},
					apiUrl().name,
					this.list_form(),
					this.current
				);
				get_zcGetGoodsReportList(data).then((res) => {
					if (res.errcode == 0) {
						this.list = res.data.list;
						if (res.data.category_list) {
							this.options = recursion(res.data.category_list, true);
						}
						this.totalCount = res.data.count;
					} else {
						this.$message.error(res.errmsg);
					}
					this.listLoading = false;
				});
			},
			//商品明细
			get_zcGetSkuDetailPurReport() {
				this.drawer_loading = true;
				let data = Object.assign(
					{
						sign: Md5(
							objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
						),
					},
					apiUrl().name,
					this.drawer_form,
					this.current_drawer
				);
				get_zcGetSkuDetailPurReport(data).then((res) => {
					if (res.errcode == 0) {
						this.drawer_list = res.data.list;
						this.chart_list = res.data.chart_list;
						this.totalCount_drawer = res.data.count;
					} else {
						this.$message.error(res.errmsg);
					}
					this.drawer_loading = false;
				});
			},
			// 重置
			reset() {
				this.$refs["userListFrom"].resetFields();
				this.establishTime = this.getNowMonth();
				this.form.supplier_id = null;
				this.form.buyer_id = null;
				if (this.moredata) {
					this.$refs["changeGoodsInput"].name = "";
				}
				this.getArticleList();
			},
			// 搜索
			getArticleList() {
				this.current.page = 1;
				this.get_zcGetGoodsReportList();
			},
			// 分页
			changeLimit(pageSize, type) {
				switch (type) {
					case 1:
						this.current.per_page = pageSize;
						this.get_zcGetGoodsReportList();
						break;
					case 2:
						this.current_drawer.per_page = pageSize;
						this.get_zcGetSkuDetailPurReport();
						break;
				}
			},
			changePage(page, type) {
				switch (type) {
					case 1:
						this.current.page = page;
						this.get_zcGetGoodsReportList();
						break;
					case 2:
						this.current_drawer.page = page;
						this.get_zcGetSkuDetailPurReport();
						break;
				}
			},

			list_form() {
				let form = JSON.parse(JSON.stringify(this.form));
				form.pid = form.category_id[0] ? form.category_id[0] : "";
				form.category_id = category(form.category_id);
				form.start_time = this.establishTime[0] ? this.establishTime[0] : "";
				form.end_time = this.establishTime[1] ? this.establishTime[1] : "";
				!form.pid ? delete form.pid : "";
				!form.category_id ? delete form.category_id : "";
				!form.mode ? delete form.mode : "";
				!form.goods_spu_id ? delete form.goods_spu_id : "";
				return form;
			},
			// 排序
			handleSort(data, ref) {
				let arr = ["arrow1", "arrow2"].filter((e) => e != ref);
				arr.map((e) => {
					this.$refs[e].selected = false;
				});
				this.form.order_by = data.label;
				this.form.order_type = data.type;
				this.get_zcGetGoodsReportList();
			},
			// 导出
			exportform() {
				let data = Object.assign(
					{
						sign: Md5(
							objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
						),
					},
					apiUrl().name,
					this.list_form()
				);
				export_purcahse_sku(data).then((res) => {
					this.exportMethod(res, "采购报表-SKU");
				});
			},
			// 商品明细导出
			export_zcExportSkuDetailPurReport() {
				let data = Object.assign(
					{
						sign: Md5(
							objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
						),
					},
					apiUrl().name,
					this.drawer_form
				);
				export_zcExportSkuDetailPurReport(data).then((res) => {
					this.exportMethod(res, "商品明细");
				});
			},
			// 采购日期选择
			dateChange(val) {
				let start = new Date(val[0]).getTime();
				let end = new Date(val[1]).getTime();
				let diff = start - end;
				if (Math.abs(diff) > 3600 * 1000 * 24 * 60) {
					this.$message.warning("选择时间跨度不能超过两个月");
					this.establishTime = this.getNowMonth();
				}
				this.get_zcGetGoodsReportList();
			},
			// 明细
			handleDetail(row) {
				this.drawer_title = row.goods_name;
				this.drawer_form = {
					start_time: "",
					end_time: "",
					goods_spu_id: row.goods_spu_id,
					date_type: this.form.date_type,
				};
				if (this.establishTime) {
					this.drawer_form.start_time = this.establishTime[0]
						? this.establishTime[0]
						: "";
					this.drawer_form.end_time = this.establishTime[1]
						? this.establishTime[1]
						: "";
				}
				this.get_zcGetSkuDetailPurReport();
				this.goods_drawer = true;
			},
			showChart() {
				let titles = [];
				let datas = [];
				this.chart_list.map((e) => {
					titles.push(e.purchase_time);
					datas.push(e.price);
				});
				this.$nextTick(() => {
					this.chartColumn(titles, datas);
				});
			},
			showChartnew() {
				this.dialogTableVisible = true;
				let titles = [];
				let datas = [];
				this.chart_list.map((e) => {
					titles.push(e.purchase_time);
					datas.push(e.price);
				});

				this.$nextTick(() => {
					this.chartColumn(titles, datas);
				});
			},
			// 图标
			// 只适用图表方法
			drawLine(dom, option) {
				if (document.getElementById(dom)) {
					let myChart = echarts.init(document.getElementById(dom));
					this.myChart = myChart;
					let resizeDiv = document.getElementById(dom);
					myChart.clear();
					myChart.setOption(option);
					let listener = function () {
						myChart.resize();
					};
					EleResize.on(resizeDiv, listener);
				}
			},
			chartColumn(titles, datas) {
				// 折线图
				let dom = "chartBar";
				let option1 = {
					graphic: [
						{
							type: "image",
							id: "logo",
							left: "center",
							top: "90",
							bounding: "raw",
							style: {
								image: this.no_data_img,
								width: 92,
								opacity: 1,
							},
						},
					],
				};
				let option2 = {
					tooltip: {
						show: true,
						trigger: "axis",
						formatter: "{a} <br/>{b} : {c}",
						axisPointer: {
							type: "cross",
							label: {
								backgroundColor: "#03A98E",
							},
						},
					},
					grid: {
						top: 20,
						bottom: 20,
						left: 60,
						right: 40,
					},
					xAxis: {
						type: "category",
						boundaryGap: false,
						axisLabel: {
							show: true,
							textStyle: {
								color: "#333",
							},
						},
						axisTick: {
							show: false,
						},
						data: titles,
					},
					yAxis: {
						axisLine: {
							lineStyle: {
								color: "rgba(107,107,107,0.37)",
							},
						},
						splitLine: {
							show: true,
							lineStyle: {
								color: "#ccc",
								type: "dashed",
							},
						},
						axisLabel: {
							show: true,
							textStyle: {
								color: "#333",
							},
						},
						axisTick: {
							show: false,
						},
						type: "value",
					},
					series: [
						{
							name: "采购均价",
							data: datas,
							symbol: "circle",
							symbolSize: 10,
							smooth: true, //这句就是让曲线变平滑的
							type: "line",
							lineStyle: {
								normal: {
									color: "#03A98E",
								},
							},
							itemStyle: {
								normal: {
									borderWidth: 3,
									borderColor: "#BAFFF4",
									color: "#03A98E",
									areaStyle: {
										color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
											{
												offset: 0,
												color: "rgba(3,169,142,0)",
											},
											{
												offset: 1,
												color: "rgba(3,169,142,0.25)",
											},
										]),
									},
								},
							},
						},
					],
				};
				let options = {};
				if (datas.length == 0) {
					options = option1;
				} else {
					options = option2;
				}
				this.drawLine(dom, options, 1);
			},
		},
	};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.mainsu {
	.mainor_form form {
		width: calc(100% - 180px);
	}
}

// 支付状态
.success {
	color: $green;
}
.unpaid {
	color: $colour_red;
}
// 订单状态
.order0 {
	color: $order_color1;
}
.order1 {
	color: $order_color2;
}
.order2 {
	color: $order_color3;
}
.order4 {
	color: $order_color4;
}
.popover_chart {
	width: 100%;
	height: 400px;
}
</style>
